<!--代码生成器-->
<!--created by lx 2023/6/7-->
<template>
  <div class="list-card-container">
    <a-card title="代码生成器" class="general-card">
      <!-- 查询表单 -->
      <TableSearch
        ref="searchRef"
        :data-source="SEARCH_FORM"
        @change="searchGenerator"
      />

      <a-space style="margin-bottom: 7px">
        <ImportTableDrawer @after-submit="searchGenerator" />
        <TableCreateModal />
      </a-space>

      <!-- 表格 -->
      <a-table
        :columns="COLUMNS_GENERATOR"
        :data="generatorList"
        row-key="id"
        :loading="loading || dataSourceLoading"
        :pagination="pagination"
        :scroll="{ x: '1000px' }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!--插槽，操作-->
        <template #operation="{ record }">
          <a-space>
            <a-popconfirm
              content="确定同步该数据吗？"
              type="warning"
              @ok="synchronizeCode(record)"
            >
              <a-link>同步</a-link>
            </a-popconfirm>
            <a-popconfirm
              content="确定删除该数据吗？"
              type="warning"
              @ok="deleteConfig(record)"
            >
              <a-link> 删除 </a-link>
            </a-popconfirm>
            <a-dropdown>
              <a-link>
                更多
                <icon-down />
              </a-link>
              <template #content>
                <a-doption @click="gotoEdit(record)">编辑</a-doption>
                <a-doption @click="previewCode(record)">预览</a-doption>
                <a-doption @click="downloadCode(record)">下载代码</a-doption>
              </template>
            </a-dropdown>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!--对话框：预览-->
    <PreviewCodeModal v-model:visible="previewing" :table-id="editingId" />
  </div>
</template>

<script lang="ts" setup name="CodegenEdit">
  import { Message, TableColumnData } from '@arco-design/web-vue';
  import {
    CodegenRecord,
    CodegenParams,
  } from '@/api/infrastructure/model/codegenModel';
  import {
    queryCodegenRecordPage,
    removeCodegenRecord,
    syncCodegenRecord,
    downloadGeneratedCode,
  } from '@/api/infrastructure/codegen';
  import { DataSourceRecord } from '@/api/infrastructure/model/dataSourceConfigModel';
  import { queryDataSourceRecord } from '@/api/infrastructure/data-source-config';
  import { useRouter } from 'vue-router';
  import { ref, onMounted, reactive } from 'vue';
  import TableSearch from '@/common/components/cac-components/advanced-search/index.vue';
  import { Pagination } from '@/types/global';
  import ImportTableDrawer from './components/import-table-drawer.vue';
  import TableCreateModal from './components/table-create-modal.vue';
  import PreviewCodeModal from './components/preview-code-modal.vue';

  const router = useRouter();
  // 查询表单
  const SEARCH_FORM: any[] = [
    { fieldName: 'tableName', labelText: '表名称', type: 'text' },
    { fieldName: 'tableComment', labelText: '表描述', type: 'text' },
    {
      fieldName: 'createTime',
      labelText: '创建时间',
      type: 'datetimeRange',
    },
  ];

  const dataSourceList = ref<DataSourceRecord[]>([]);
  const dataSourceLoading = ref<boolean>(false);
  const listDataSource = async () => {
    dataSourceLoading.value = true;
    try {
      const { data } = await queryDataSourceRecord();
      dataSourceList.value = data;
    } finally {
      dataSourceLoading.value = false;
    }
  };

  const loading = ref<boolean>(false);

  const searchRef = ref<any>();
  // 分页，默认第1页，每页10条
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    showPageSize: true,
    showTotal: true,
  };
  const pagination = reactive({
    ...basePagination,
  });

  /**
   * @method
   * @description 页码发生变化触发
   */
  const onPageChange = (current: number) => {
    pagination.current = current;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 数据条数发生变化触发
   */
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };

  // func: 查询代码(下载包)
  const searchGenerator = async (reqdata: CodegenRecord = {}) => {
    const params: CodegenParams = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...reqdata,
    };
    loading.value = true;
    try {
      const { data } = await queryCodegenRecordPage(params);
      generatorList.value = data.list;
      pagination.total = Number(data.total);
    } finally {
      loading.value = false;
    }
  };

  onMounted(() => {
    listDataSource();
    searchGenerator();
  });

  // 表格
  const generatorList = ref<CodegenRecord[]>([]);
  const COLUMNS_GENERATOR: TableColumnData[] = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      width: 80,
      render: ({ rowIndex }) => rowIndex + 1,
      fixed: 'left',
    },
    {
      title: '数据源',
      dataIndex: 'dataSource',
      render: ({ record }) =>
        dataSourceList.value.find(
          (elem: any) => elem.id === record.dataSourceConfigId
        )?.name,
      width: 120,
      ellipsis: true,
    },
    {
      title: '表名称',
      dataIndex: 'tableName',
      width: 120,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '表描述',
      dataIndex: 'tableComment',
      width: 150,
      tooltip: true,
      ellipsis: true,
    },
    {
      title: '实体',
      dataIndex: 'className',
      width: 180,
      tooltip: true,
      ellipsis: true,
    },
    { title: '创建时间', dataIndex: 'createTime', width: 180 },
    { title: '更新时间', dataIndex: 'updateTime', width: 180 },
    {
      title: '操作',
      dataIndex: 'operation',
      slotName: 'operation',
      width: 180,
      align: 'center',
      fixed: 'right',
    },
  ];

  // func: 删除一条记录
  const deleteConfig = async (row: CodegenRecord) => {
    try {
      await removeCodegenRecord(row.id as string);
      Message.success('操作成功');
    } finally {
      searchGenerator();
    }
  };
  // func: 同步代码
  const synchronizeCode = async (row: CodegenRecord) => {
    try {
      await syncCodegenRecord(row.id as string);
      Message.success('同步成功');
    } finally {
      // finally
    }
  };

  const gotoEdit = (record: CodegenRecord) => {
    router.push({ path: '/codegen/edit', query: { id: record.id } });
  };

  const previewing = ref<boolean>(false);
  const editingId = ref<string>('');
  const previewCode = async (record: CodegenRecord) => {
    editingId.value = record.id || '';
    previewing.value = true;
  };
  const downloadCode = async (record: CodegenRecord) => {
    try {
      const res = (await downloadGeneratedCode(record.id as string)) as any;
      const elink = document.createElement('a');
      elink.download = `codegen-${record.className}.zip`;
      elink.style.display = 'none';
      const blob = new Blob([res], { type: 'application/zip' });
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      document.body.removeChild(elink);
    } finally {
      // empty
    }
  };
</script>

<style lang="less" scoped>
  .list-card-container {
    padding: 20px;
    border-radius: var(--border-radius-default);
  }
</style>
